#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
@version: Anaconda
@author: longchaohuo
@contact: 460958592@qq.com
@software: PyCharm
@file: UCGS_Landsat_Download
@time: 2022/9/30  下午 14:23
参考文档：https://github.com/yannforget/landsatxplore；https://pypi.org/project/landsatxplore/
"""
from osgeo import ogr
import os
import landsatxplore.api
from landsatxplore.earthexplorer import EarthExplorer
import json
# 求geojson中图形的最小外接矩形'
def circumscribed_rectangle(geojson_path):
    json_driver = ogr.GetDriverByName('GeoJSON')
    json_ds = json_driver.Open(geojson_path)
    cs=json_ds.GetLayerByIndex(0)
    for row in cs:
        k=row.geometry()
        data_num= k.GetEnvelope()
        xmin = data_num[0]
        xmax =data_num[1]
        ymin = data_num[2]
        ymax = data_num[3]
    return xmin, xmax, ymin, ymax
#登录UCGS及参数设置
def request_UCGS(username, password, product, xmin, ymin, xmax, ymax, start_date, end_date, cloud_max):
    #API连接
    api = landsatxplore.api.API(username, password)

    scenes = api.search(
        dataset=product,
        bbox=(xmin, ymin, xmax, ymax),
        start_date=start_date,
        end_date=end_date,
        max_cloud_cover=cloud_max,)
    print(f'共有产品数量{len(scenes)}')
    api.logout()
    return scenes
# 下载主函数
def download_UCGS_data(username, password, Landsat_name, output_dir):
    Earth_Down = EarthExplorer(username, password)
    for scene in Landsat_name:
        # print(scene)
        # name = scene['product_id']
        ID = scene['display_id']
        # print(f"下载的数据为{scene['landsat_product_id']}")
        if not os.path.isfile(output_dir + ID+".zip"):
            print(f'本地无:{output_dir + ID}.zip 的完整文件，尝试下载')
            Earth_Down.download(identifier=ID, output_dir=output_dir)
    Earth_Down.logout()



if __name__ == '__main__':
    #https://earthexplorer.usgs.gov/的账号及密码
    username = 'GISer2.5'
    password = '123456789GIS'
    # 产品类别
    product = 'landsat_etm_c2_l2'
    # 下载范围
    geojson_path = r"G:\哨兵数据库\珠江口\2016\map.geojson"
    xmin, xmax, ymin, ymax = circumscribed_rectangle(geojson_path)
    # 起始及结束时间
    start_date = '2000-01-01'
    end_date = '2022-12-31'
    # 云量大小（<=cloud_max%）
    cloud_max = 90
    # 输出文件夹
    output_dir = r'G:\Lansat数据下载'
    Landsat_name = request_UCGS(username, password, product, xmin, ymin, xmax, ymax, start_date, end_date, cloud_max)
    download_UCGS_data(username, password, Landsat_name, output_dir)